<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose title="详情" :width="1000">
    <div class="detail-wrap">
      <p v-if="detail.tenderDescType === 'txt'">{{ detail.tenderDesc }}</p>
      <p v-else-if="detail.tenderDescType === 'html'" v-html="detail.tenderDesc"></p>
      <template v-else-if="detail.tenderDescType === 'image'">
        <img v-for="(url, index) in detail.imageUrlList" :key="index" :src="url" alt="图片" />
      </template>
      <template v-else-if="detail.tenderDescType === 'pdf'">
        <iframe v-if="detail.pdfUrl" :src="`${detail.pdfUrl}#navpanes=0`" width="100%" height="600px"></iframe>
      </template>
      <p v-else>{{ detail.tenderDesc }}</p>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { getDetailInfo, DownloadImagApi } from '@/views/information/TenderInformation.api';

  const detail = ref({});

  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ loading: true });
    detail.value = {};
    try {
      const res = await getDetailInfo(data.id);
      const responseData = { ...res };

      if (responseData.tenderDescType === 'image' && responseData.tenderDescList) {
        // 使用Promise.all等待所有图片URL获取完成
        const imagePromises = responseData.tenderDescList.map((id) => handleDownload(id));
        responseData.imageUrlList = (await Promise.all(imagePromises)).filter(Boolean);
      }

      if (responseData.tenderDescType === 'pdf') {
        responseData.pdfUrl = await handleDownload(responseData.tenderDesc);
        responseData.pdfUrl = await DownloadImagApi({ id: responseData.tenderDesc }).then((res) => {
          const url = window.URL.createObjectURL(new Blob([res], { type: 'application/pdf' })); //获得一个pdf的url对象
          // URL.revokeObjectURL(url); //释放内存
          return url;
        });
      }

      // 所有图片URL都获取完成后再更新detail
      detail.value = responseData;
    } catch (error) {
      console.error('获取详情失败:', error);
    } finally {
      setModalProps({ loading: false });
    }
  });

  function handleDownload(id = '') {
    return DownloadImagApi({ id })
      .then((res) => {
        const url = URL.createObjectURL(res);
        return url;
      })
      .catch(() => {
        return '';
      });
  }
</script>

<style lang="less" scoped>
  .detail-wrap {
    width: 100%;
    height: 100%;
    p {
      white-space: pre-wrap;
      word-break: break-word;
    }
    img {
      width: 100%;
    }
  }
</style>
